<template>
	<view>
		<u-navbar title="好友申请">
			<navigator slot="right" url="/pages/friend/add" class="u-m-r-30">
				<text class="text-blue">添加</text>
			</navigator>
		</u-navbar>
		<view class="u-m-t-20">
			<block v-for="(item,index) in petitions.list" :key="index">
				<view @tap="toUserInfo(item)" v-if="userId==item.toUserId" class="bg-white u-flex u-p-x-30 u-p-y-14 u-border-bottom">
					<u-avatar :src="item.avatarUrl" mode="square">
					</u-avatar>
					<view class="u-m-x-20 u-flex-1" style="width: 100rpx;">
						<view class="">
							<text class="u-font-30">{{item.userName}}</text>
						</view>
						<view class="u-line-1">
							<text class="u-font-26 text-gray">{{item.remark}}</text>
						</view>
					</view>
					<view class="u-flex" @tap.stop v-if="item.status==0">
						<view>
							<u-button size="mini" :plain="true" type="primary" @click="agree(item)">同意</u-button>
						</view>
						<view class="u-m-l-10">
							<u-button size="mini" :plain="true" type="default" @click="disagree(item)">拒绝</u-button>
						</view>
					</view>
					<view class="u-flex" v-else>
						<text v-if="item.status==1" class="text-blue u-font-24">已同意</text>
						<text v-if="item.status==2" class="text-gray u-font-24">已拒绝</text>
					</view>
				</view>
				<view @tap="toUserInfo(item)" v-else class="bg-white u-flex u-p-x-30 u-p-y-14 u-border-bottom">
					<u-avatar :src="item.toAvatarUrl" mode="square">
					</u-avatar>
					<view class="u-m-x-20 u-flex-1" style="width: 100rpx;">
						<view class="">
							<text class="u-font-30">{{item.toUserName}}</text>
						</view>
						<view class="u-line-1">
							<text class="u-font-26 text-gray">{{item.remark}}</text>
						</view>
					</view>
					<view class="u-flex">
						<text v-if="item.status==0" class="text-blue u-font-24">等待对方确认</text>
						<text v-if="item.status==1" class="text-blue u-font-24">已同意</text>
						<text v-if="item.status==2" class="text-gray u-font-24">已拒绝</text>
					</view>
				
				</view>
			</block>
		</view>
		<u-modal
			v-model="ask.show"
			title="拒绝申请" 
			confirm-text="回复"
			showCancelButton
			@cancel="reject"
			@confirm="resolve"
		>
			<view class="u-p-y-20 u-p-x-30">
				<textarea v-model="ask.content" class="textarea" maxlength="30" placeholder="回复(30字内)" />
			</view>
		</u-modal>
		<real-dialog v-model="realAsk.show"></real-dialog>
		
	</view>
</template>

<script>
	import {toast,delay} from "@/utils/util.js"
	import {
		fetchApplyList,
		APPLY_STATE,
		handleApply
	} from "@/api/addr.js"
	import chat, {
		msgTypes,
		dictateTypes
	} from "@/IM/index.js"
	import realDialog from "@/components/dialogs/realname/index.vue"
	import {mapGetters,mapActions} from "vuex"
	export default {
		components:{
			realDialog,
		},
		data() {
			return {
				petitions: {
					list: [],
					pageNo: 1,
					pageSize: 20,
					loading: false,
					nomore: false
				},
				ask:{
					show:false,
					content:''
				},
				bridge:null,
				lock:false,
				realAsk:{
					show:false,
				},
			};
		},
		computed:{
			...mapGetters('user',['userId','isReal'])
		},
		onLoad() {
			this.resetPetitions()
		},
		async onPullDownRefresh() {
			try{
				await this.resetPetitions()
			}finally{
				uni.stopPullDownRefresh()
			}
		},
		onReachBottom() {
			this.morePetitions()
		},
		methods: {
			...mapActions('addr',['fetchAllFriends','loadOneFriend']),
			...mapActions('chat', ['sendMessage','saveHistory','setConversation']),
			realGuard(){
				if(!this.isReal){
					this.realAsk.show = true
					throw new Error('请完成实名认证')
				}
			},
			toUserInfo(item){
				if(this.userId==item.toUserId){ 
					uni.navigateTo({
						url:`/pages/user/info?id=${item.userId}`,
						success:({eventChannel})=>{
							eventChannel.emit('setExt',item)
						}
					})
				}else{
					uni.navigateTo({
						url:`/pages/user/info?id=${item.toUserId}`,
						success(res){
						}
					})
				}
			},
			async disagree(item){
				
				if(this.lock){
					throw new Error('正在请求中')
				}
				try{
					this.lock = true
					await new Promise((resolve,reject)=>{
						this.bridge={
							resolve,
							reject
						}
						this.ask.show = true
						this.ask.content = ''
					})
					await handleApply({
						id:item.id,
						status:APPLY_STATE.refuse,
						reason:this.ask.content
					})
					item.status = APPLY_STATE.refuse
					await delay(200)
					toast('已拒绝')
				}finally{
					this.lock = false
				}
			},
			async agree(item){
				
				if(this.lock){
					throw new Error('正在请求中')
				}
				try{
					this.lock = true
					await handleApply({
						id:item.id,
						status:APPLY_STATE.agree
					})
					item.status = APPLY_STATE.agree
					this.loadOneFriend(item.userId)
					this.sendAgree({
						id:item.userId,
						avatar:item.avatarUrl,
						name:item.userName
					})
					this.informAgree({id:item.userId})
					await delay(200)
					toast('已同意')
				}finally{
					this.lock = false
				}
			},
			informAgree({id}){
				chat.dictate({
					to:id,
					msgType:dictateTypes.addFriend,
					content:'同意了你的好友申请',
					extras:{}
				})
			},
			async sendAgree({id,avatar,name}){
				const msg = chat.createMessage({
					to: id,
					content: '我通过了你的朋友验证请求，现在我们可以开始聊天了',
					msgType: msgTypes.TEXT
				})
				this.setConversation({
					id,
					avatar,
					name,
					type:2,
					lastMessage:msg
				})
				msg.readBody = {readCount:0,unreadCount:1}
				msg.status = 'loading';
				try {
					await this.sendMessage({
						message: msg,
						id:id
					})
					await chat.send(msg)
					msg.status = 'success';
					this.saveHistory()
				} catch (e) {
					msg.status = 'error';
				}
			},
			resolve(e){
				this.bridge&&this.bridge.resolve&&this.bridge.resolve(e)
			},
			reject(e){
				this.bridge&&this.bridge.reject&&this.bridge.reject(e)
			},
			async resetPetitions() {
				this.petitions.nomore = false
				this.petitions.list = []
				this.petitions.pageNo = 1
				await this.morePetitions()
			},
			async morePetitions() {
				const list = await this.getPetitions();
				this.petitions.list.push(...list)
			},
			async getPetitions() {
				if (this.petitions.loading) {
					throw new Error('正在请求中')
				}
				try {
					if (this.petitions.nomore) {
						return []
					}
					this.petitions.loading = true
					const list = await fetchApplyList(this.petitions)
					if (!list || list.length < this.petitions.pageSize) {
						this.petitions.nomore = true
					} else {
						this.petitions.pageNo++
					}
					return list
				} finally {
					this.petitions.loading = false
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.textarea{
		width: 100%;
		height: 160rpx;
		background-color: #F5F5F5;
		padding: 20rpx;
		border-radius: 10rpx;
		font-size: 28rpx;
	}
</style>
